package bam.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import bam.dao.AppSystemDao;
import bam.entityBam.Zzroleuser;
import bam.util.PagingUtil;

public class AppStystemDaoIpml extends HibernateDaoSupport implements AppSystemDao{

	public void selectSystemUser(PagingUtil<Zzroleuser> pu, Zzroleuser zzroleuser) throws Exception {
		pu.setLogCount(scount(zzroleuser));
		
		String  sql = "select * From zzroleuser where (phone like ? " +
				"or user_name like ?) ";
					if(zzroleuser.getZzrole()!=null){
					sql = sql +"and user_role = ? ";
					}
					if(zzroleuser.getAreaId()!=0){
					sql = sql + "and area_id = ?";
					}		
		
		Query query = this.getSession().createSQLQuery(sql).addEntity(Zzroleuser.class);
		query.setParameter(0, "%"+zzroleuser.getPhone()+"%");
		query.setParameter(1, "%"+zzroleuser.getPhone()+"%");
		if(zzroleuser.getZzrole()!=null&&zzroleuser.getZzrole().getId()!=null){
			query.setParameter(2, zzroleuser.getZzrole().getId());
		}
		if(zzroleuser.getZzrole()!=null&&zzroleuser.getAreaId()!=0&&
				zzroleuser.getZzrole().getId()!=null){
			query.setParameter(3, zzroleuser.getZzrole().getId());
		}else if(zzroleuser.getAreaId()!=0){
			query.setParameter(2,zzroleuser.getAreaId());
		}
		int start=(pu.getPageNo()-1)*pu.getPageSize();
		int size = pu.getPageSize();
		query.setFirstResult(start);
		query.setMaxResults(size);
		List list = query.list();
		pu.setList(list);
	}
	
	
	private int scount(Zzroleuser zzroleuser) throws Exception {
		
		String  sql = "select count(id) From zzroleuser where (phone like ? " +
						"or user_name like ?) ";
				if(zzroleuser.getZzrole()!=null){
				sql = sql +"and user_role = ? ";
				}
				if(zzroleuser.getAreaId()!=0){
				sql = sql + "and area_id = ?";
				}		
		
		Query query = this.getSession().createSQLQuery(sql);
		query.setParameter(0, "%"+zzroleuser.getPhone()+"%");
		query.setParameter(1, "%"+zzroleuser.getPhone()+"%");
		if(zzroleuser.getZzrole()!=null&&zzroleuser.getZzrole().getId()!=null){
		query.setParameter(2, zzroleuser.getZzrole().getId());
		}
		if(zzroleuser.getZzrole()!=null&&zzroleuser.getAreaId()!=0&&
			zzroleuser.getZzrole().getId()!=null){
		query.setParameter(3, zzroleuser.getZzrole().getId());
		}else if(zzroleuser.getAreaId()!=0){
		query.setParameter(2,zzroleuser.getAreaId());
		}
		System.out.println(query.uniqueResult());
		Integer uniqueResult = Integer.parseInt(query.uniqueResult().toString());
		return uniqueResult;
	}


	public Zzroleuser selectRoleuser(int userid) throws Exception {
		Query query = this.getSession().createQuery("From Zzroleuser where users_id=?");
		query.setParameter(0, userid);
		List<Zzroleuser> list = query.list();
		return list.isEmpty()?null:list.get(0);
	}
}
